package web.common.ehcache;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jfinal.plugin.ehcache.CacheKit;

import web.common.enums.CacheNameEnum;
import web.model.Dict;

/**
 * 字典工具类
 * @author ThinkGem
 * @version 2013-5-29
 */
public class DictCache {
	public static String getDictLabel(String value, String type, String defaultValue) {
		if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(value)){
			for (Dict dict : getDictList(type)){
				if (type.equals(dict.getType()) && value.equals(dict.getValue())){
					return dict.getLabel();
				}
			}
		}
		return defaultValue;
	}
	public static String getDictLabels(String values, String type, String defaultValue){
		if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(values)){
			List<String> valueList = Lists.newArrayList();
			for (String value : StringUtils.split(values, ",")){
				valueList.add(getDictLabel(value, type, defaultValue));
			}
			return StringUtils.join(valueList, ",");
		}
		return defaultValue;
	}
	public static String getDictValue(String label, String type, String defaultLabel){
		if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(label)){
			for (Dict dict : getDictList(type)){
				if (type.equals(dict.getType()) && label.equals(dict.getLabel())){
					return dict.getValue();
				}
			}
		}
		return defaultLabel;
	}

	public static Map<String, Dict> getDictMap(String type) {
		Map<String, Dict> dictmap = Maps.newHashMap();
		if (StringUtils.isNotBlank(type)) {
			for (Dict dict : getDictList(type)) {
				dictmap.put(dict.getValue(), dict);
			}
		}
		return dictmap;
	}
	public static List<Dict> getDictList(String type){
		Map<String, List<Dict>> dictMap = CacheKit.get(CacheNameEnum.DICT.getName(),
				CacheNameEnum.DICT.getMapName());
		if (dictMap==null){
			dictMap = Maps.newHashMap();
			List<Dict> dicts = Dict.dao
					.find("SELECT * FROM dict WHERE del_flag = 0 ORDER BY type, sort, modify_time DESC");
			for (Dict dict : dicts) {
				List<Dict> dictList = dictMap.get(dict.getType());
				if (dictList != null){
					dictList.add(dict);
				}else{
					dictMap.put(dict.getType(), Lists.newArrayList(dict));
				}
			}
			CacheKit.put(CacheNameEnum.DICT.getName(), CacheNameEnum.DICT.getMapName(), dictMap);
		}
		List<Dict> dictList = dictMap.get(type);
		if (dictList == null){
			dictList = Lists.newArrayList();
		}
		return dictList;
	}
	
	/**
	 * 返回字典列表（JSON）
	 * @param type
	 * @return
	 */
	public static String getDictListJson(String type){
		return JSON.toJSONString(getDictList(type));
	}
	
}
